/* eslint-disable */
import { ForbiddenException, Injectable } from '@nestjs/common';
import { User } from './entities/user.entity';
import { Profile } from './entities/profile.entity';

import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { RolesService } from '../roles/roles.service';
import * as crypto from 'crypto';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,

    @InjectRepository(Profile)
    private readonly profileRepository: Repository<Profile>,

    private rolesService: RolesService,
  ) {}
  // 创建用户
  async create(user: Partial<User>) {
    const hash = crypto.createHash('md5');
    const tempUser = this.userRepository.create(user);
    tempUser.password = hash.update(tempUser.password).digest('hex');
    const curRoles = user.roles || [3];
    tempUser.roles = await this.rolesService.findByIds(curRoles);
    return await this.userRepository.save(tempUser);
  }
  // 新增用户
  async addUser(body) {
    const { username, password, role, ...profileData } = body;
    const hash = crypto.createHash('md5');
    const user = await this.findOne(null, username);
    if (user) {
      throw new ForbiddenException('当前用户已注册');
    }
    const tempUser = await this.userRepository.create({ username, password });
    tempUser.password = hash.update(tempUser.password).digest('hex');
    const tempProfile = await this.profileRepository.create(profileData);
    // @ts-ignore
    tempUser.profile = await this.profileRepository.save(tempProfile);
    // @ts-ignore
    tempUser.roles = await this.rolesService.findByIds([role]);
    return await this.userRepository.save(tempUser);
  }
  async findAll(query) {
    const { pageSize = 10, pageNum = 1, ...params } = query;
    const user = this.userRepository.createQueryBuilder('user');
    if (params.username) {
      user.where(`user.username LIKE :username`, {
        username: `%${params.username}%`,
      });
    }
    // if(params.code ){
    //   user.where('user.code = :code',{code:params.code})
    // }
    const profileFilter = ['phone', 'nickname', 'sex', 'status'];
    const profile = user.leftJoinAndSelect('user.profile', 'profile');
    profileFilter.forEach((prof) => {
      if (params[prof]) {
        profile.andWhere(`profile.${prof} LIKE :${prof}`, {
          [prof]: `%${params[prof]}%`,
        });
      }
    });
    const roles = profile.leftJoinAndSelect('user.roles', 'roles');
    const result = await roles
      .skip((pageNum - 1) * pageSize)
      .take(pageSize)
      .getManyAndCount();
    return { total: result[1], rows: result[0] };
  }
  findUserByCode(code) {
    console.log(code);
    const res = this.userRepository.find({ where: { code } });
    console.log('findUserByCode', res);
    return res;
  }
  //
  findOne(id: number, username?: string) {
    return this.userRepository.findOne({ where: { username: username, id } ,relations:['profile']});
  }

  async update(body) {
    const { role, user, ...profile } = body;
    const { id, ...profileParam } = profile.profile;
    const tempUser = await this.userRepository.findOne({ where: { id: user } });
    console.log('profileParam', id, profileParam);
    if (id) {
      this.profileRepository.update(id, profileParam);
    } else {
      const tempProfile = await this.profileRepository.create(profileParam);
      // @ts-ignore
      tempUser.profile = await this.profileRepository.save(tempProfile);
    }
    if (role) {
      tempUser.roles = await this.rolesService.findByIds([role]);
    }
    return this.userRepository.save(tempUser);
  }

  remove(ids: string) {
    ids.split(',').forEach((id) => this.userRepository.delete(+id));
    return '删除成功';
  }
  // 获取好友
  findFriend(code) {
    return this.userRepository
      .createQueryBuilder('user')
      .where('user.code LIKE :code', { code: `%${code}%` })
      .leftJoinAndSelect('user.profile', 'profile')
      .getMany();
  }
}
